<?php
include_once 'application/application.php';




class Page_botconfig {



    public  $action;
    public  $error;
    private $conf_path;
    private $is_win;


    public function __construct() {
        $this->action = Arr::getValue($_POST, 'action', false);
        
        $this->is_win = (strpos(strtoupper(Arr::getValue($_SERVER, 'PATH', '')),  'WINDOWS'));
        
        $this->conf_path = $this->is_win? 
                "E:/WWW/reports/clients_program_update/config_data/" : 
                "/var/reports/clients_program_update/config_data/";
        
        
        
        DB::connect();
        if (!DB::state()) {
            $this->error = DB::getError();
        }
    }

    public function __destruct() {

    }
    
    
    
    
    private function readDir() {
        $J = new JSON();
        if (!is_dir($this->conf_path)) return $J->error('Нет доступа к директории');
        
        $all = scandir($this->conf_path);
        if (!is_array($all)) return $J->error('Файлы недоступны');
        
        $files = array();
        foreach ($all as $filewithext) {
            list($name,$ext) = explode('.', $filewithext, 2);
            if (!$name || !$ext) continue;
            if (strtolower($ext) != 'xml') continue;
            if (!isValidDataTableName($name)) continue;
            $files[$name] = $name;
        }
        $J->files = $files;
        return $J;
    }
    
    
    private function readFilesInfo($filenames) {
        $out = array();
        
        if (!is_array($filenames)) return $out;
        foreach ($filenames as $name) {
            $file = $name.'.xml';
            $fpath = $this->conf_path.$file;
            $out[$name] = array(
                'file'      => $file,
                'lastmod'   => false,
                'size'      => false
            );
            
            if (is_file($fpath)) {
                $stat = @stat($fpath);
                if ($stat) { 
                    $lastModified = Arr::getValue($stat, 'mtime', FALSE);
                    if ($lastModified) $out[$name]['lastmod'] = date('Y-m-d H:i:s', $lastModified);
                    $out[$name]['size'] = Arr::getValue($stat, 'size', FALSE);
                }
            }
        }
        
        return $out;
    }
    
    private function readFile($name) {
        $J = new JSON();
        
        $file = $name.'.xml';
        $fpath = $this->conf_path.$file;
        if (!is_file($fpath)) return $J->error('Файл не найден.');
        
        $arr = @file($fpath);
        if (!is_array($arr)) $J->error('Файл не доступен.');
        
        $J->content = str_replace("\r",'', join("", $arr));
        
        return $J;
    }
    
    
    
    
    
    
    public function getContent() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');
        
        $J->readVar('action');
        $file = mysql_escape_string($J->readVar('file'));
        
        
        if ($this->error) return $J->error($this->error);
        
        $JD = $this->readDir();
        if (!$JD->getState()) return $J->error($JD->getErrorString());
        
        $files = $JD->files;
        if (!Arr::getValue($files, $file, false)) return $J->error('Файл не найден');
        
        $JC = $this->readFile($file);
        if (!$JC->getState()) return $J->error($JC->getErrorString());
        
        $J->content = $JC->content;
        return $J;
    }
    
    public function saveContent() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');
        
        $J->readVar('action');
        $file = mysql_escape_string($J->readVar('file'));
        $text = $J->readVar('text');
        
        
        if ($this->error) return $J->error($this->error);
        if (!$text) return $J->error('Файл не может быть пустым!');
        
        
        $JD = $this->readDir();
        if (!$JD->getState()) return $J->error($JD->getErrorString());
        
        $files = $JD->files;
        if (!Arr::getValue($files, $file, false)) return $J->error('Файл не найден');
        
        $fpath = $this->conf_path.$file.'.xml';
        if (!@file_put_contents($fpath, $text)) {
            return $J->error('Ошибка записи в файл');
        }
        
        $J->saved = $this->readFilesInfo(array($file => $file));
        return $J;
    }
    
    
    
    
    
    
    
    
    
    
    
    

    public function outPage() {
        $JD = $this->readDir();
        $params = array('files'=>array(), 'error'=>$this->error);
        
        if (!$JD->getState()) $params['error'] .= $JD->getErrorString();
        else $params['files'] = $this->readFilesInfo ($JD->files);
        
        

        $this->printOut(includeFile(APP_PAGE_PARTS.'page_botconfig.php', $params));
    }


    
    


    public function printOut( $content = '' ) {

        include_once APP_PAGE_PARTS.'header.php';
        echo Navbar::getHorisontalBar();
        echo Auth::loginForm(true);

        $params = array(
            'leftmenu'  => Navbar::getVerticalBar('leftmenu'),//includeFile(APP_PAGE_PARTS.'leftmenu.php'),
            'content'   => $content? $content : ''
        );
        include APP_PAGE_PARTS.'columns.php';

        include_once APP_PAGE_PARTS.'footer.php';
        die();
    }



}

$page = new Page_botconfig();

Navbar::$expanded = 'lm-sys-bot';
        

if ($page->action) {
    if ($page->action == ACTIONS::BOTCONFIG_GETTEXT) echo $page->getContent();
    if ($page->action == ACTIONS::BOTCONFIG_SAVETEXT) echo $page->saveContent();
}
else  {
    if (!Auth::isLogged()) reLocate ('index.php');
    
    Navbar::$active = 'botconfig';
    $page->outPage();
}
?>